package proxy.dynamicproxy;

import org.junit.Assert;
import proxy.factory.PCFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

public class TaobaoProxy implements PCFactory {

    /**
     * 被代理的对象
     */
    private PCFactory pcFactory = null;

    public void setPcFactory(PCFactory pcFactory) {
        this.pcFactory = pcFactory;
    }

    @Override
    public int sell(int amount) {
        // 被代理的对象不允许为空
        Assert.assertNotNull(pcFactory);

        InvocationHandler handler = new PCFactoryInvocationHandler(pcFactory);
        Class<? extends PCFactory> pcFactoryClass = pcFactory.getClass();
        PCFactory pcFactoryProxy = (PCFactory) Proxy.newProxyInstance(pcFactoryClass.getClassLoader(), pcFactoryClass.getInterfaces(), handler);

        int price = 0;
        if (pcFactoryProxy != null) {
            price = pcFactoryProxy.sell(1);
            System.out.println("淘宝使用动态代理卖出PC电脑,售价：" + price);
        }

        return price;
    }
}
